﻿using MyBasicLib.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyBasicLib.Collections.Generic
{
    public class ModifiedTimeCache : ReaderWriterCache<String, DateTime>
    {
        public static ModifiedTimeCache Instance = new ModifiedTimeCache();
        public DateTime GetLastModifiedTime(string key)
        {
            rwLock.EnterReadLock();
            try
            {
                DateTime date;
                    
                Cache.TryGetValue(key, out date);
                return date;
            }
            finally
            {
                rwLock.ExitReadLock();
            }
        }
        public void UpdateItem(string key)
        {
            rwLock.EnterWriteLock();
            try
            {
                Cache[key] = DateTime.UtcNow;
            }
            finally
            {
                rwLock.ExitWriteLock();
            }
        }
        public override void InvalidateItem(string key)
        {
            rwLock.EnterWriteLock();
            try
            {
                Cache.Remove(key);
            }
            finally
            {
                rwLock.ExitWriteLock();
            }
        }

        public void InvalidateItemByPattern(string keyPattern)
        {
            System.Threading.ThreadPool.QueueUserWorkItem(o =>
            {
                String[] keys;
                rwLock.EnterReadLock();
                try
                {
                    keys = Cache.Keys.Where(k => k.IndexOf(keyPattern, StringComparison.OrdinalIgnoreCase) >= 0).ToArray();
                }
                finally
                {
                    rwLock.ExitReadLock();
                }
                foreach (var k in keys)
                    InvalidateItem(k);
            });
        }
    }

}
